package me.tingyugetc.crawler.fetcher;

import me.tingyugetc.crawler.fetcher.authentication.FormLogin;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class PageFetcher {

    private CloseableHttpClient httpClient;
    private BasicCookieStore cookieStore;

    public PageFetcher() {
        this.cookieStore = new BasicCookieStore();
        this.httpClient = HttpClients.custom()
                .setDefaultCookieStore(this.cookieStore)
                .build();
    }

    public String fetcher(String urlPath) throws Exception {
        if (urlPath.length() == 0) {
            throw new Exception("URL不能为空");
        }

        String html;
        HttpGet httpGet = new HttpGet(urlPath);

        try (CloseableHttpResponse response = this.httpClient.execute(httpGet)) {
            HttpEntity entity = response.getEntity();
            html = EntityUtils.toString(entity);
        } finally {
            httpGet.releaseConnection();
        }

        return html;
    }

    public HttpEntity doFormLogin(FormLogin formLogin) throws Exception {
        if (formLogin == null) {
            throw new Exception("表单数据不能为空");
        }

        HttpEntity entity;
        RequestBuilder loginRequest = RequestBuilder.post().setUri(new URI(formLogin.getLoginUrl()));
        formLogin.getFormField().forEach(loginRequest::addParameter);
        HttpUriRequest httpUriRequest = loginRequest.build();

        try (CloseableHttpResponse response = this.httpClient.execute(httpUriRequest)) {
            entity = response.getEntity();
        }
        return entity;
    }

    public void closeClient() {
        try {
            this.httpClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public CloseableHttpClient getHttpClient() {
        return httpClient;
    }

    public void setHttpClient(CloseableHttpClient httpClient) {
        this.httpClient = httpClient;
    }

    public BasicCookieStore getCookieStore() {
        return cookieStore;
    }

    public void setCookieStore(BasicCookieStore cookieStore) {
        this.cookieStore = cookieStore;
    }
}
